package org.zxxxt.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.zxxxt.shortlink.admin.common.biz.user.UserContext;
import org.zxxxt.shortlink.admin.dao.entity.GroupDO;
import org.zxxxt.shortlink.admin.dao.mapper.GroupMapper;
import org.zxxxt.shortlink.admin.dto.req.GroupSortReqDTO;
import org.zxxxt.shortlink.admin.dto.req.GroupUpdateReqDTO;
import org.zxxxt.shortlink.admin.dto.resp.GroupRespDTO;
import org.zxxxt.shortlink.admin.remote.ShortLinkRemoteService;
import org.zxxxt.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import org.zxxxt.shortlink.admin.service.GroupService;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 短链接分组实现层
 */
@Slf4j
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    /**
     * 后续重构 OpenFeign
     */
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {};


    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(),groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        String gid;
        while(true){
            gid = RandomUtil.randomString(6);
            if(hasGid(username,gid)){
                break;
            }
        }
        GroupDO build = GroupDO.builder()
                .gid(gid)
                .name(groupName)
                .username(username)
                .sortOrder(0)
                .build();
        baseMapper.insert(build);

    }

    private boolean hasGid(String username, String gid){
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag,0)
                //TODO 用户名
                .eq(GroupDO::getName, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO groupDO = baseMapper.selectOne(eq);
        return groupDO==null;
    }

    @Override
    public List<GroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0)
                .orderByAsc(GroupDO::getSortOrder)
                .orderByAsc(GroupDO::getUpdateTime);
        List<GroupDO> groups = baseMapper.selectList(queryWrapper);
        List<ShortLinkGroupCountQueryRespDTO> gids = shortLinkRemoteService.listGroupShortLinkCount(groups.stream().map(GroupDO::getGid).toList()).getData();
        List<GroupRespDTO> results = BeanUtil.copyToList(groups, GroupRespDTO.class);
        Map<String, Integer> counts = gids.stream().collect(Collectors.toMap(ShortLinkGroupCountQueryRespDTO::getGid, ShortLinkGroupCountQueryRespDTO::getShortLinkCount));
        return results.stream().peek(result -> result.setShortLinkCount(counts.get(result.getGid()))).toList();
    }

    @Override
    public void updateGroup(GroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO =  new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,eq);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO =  new GroupDO();
        groupDO.setName(UserContext.getUsername());
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO,eq);
    }

    @Override
    public void sortGrooup(List<GroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDO build = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(build,updateWrapper);
        });
    }
}
